import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Device, CreateDeviceRequest } from '@/types'
import { deviceAPI } from '@/utils/api'

export const useDevicesStore = defineStore('devices', () => {
  // 状态
  const devices = ref<Device[]>([])
  const loading = ref(false)
  const selectedDevices = ref<string[]>([])

  // Getters
  const deviceCount = computed(() => devices.value.length)
  const onlineDeviceCount = computed(() => 
    devices.value.filter(device => device.status === 'online').length
  )
  const offlineDeviceCount = computed(() => 
    devices.value.filter(device => device.status === 'offline').length
  )
  const busyDeviceCount = computed(() => 
    devices.value.filter(device => device.status === 'busy').length
  )

  const devicesByPlatform = computed(() => {
    const grouped = devices.value.reduce((acc, device) => {
      if (!acc[device.platform]) {
        acc[device.platform] = []
      }
      acc[device.platform].push(device)
      return acc
    }, {} as Record<string, Device[]>)
    return grouped
  })

  const devicesByType = computed(() => {
    const grouped = devices.value.reduce((acc, device) => {
      if (!acc[device.device_type]) {
        acc[device.device_type] = []
      }
      acc[device.device_type].push(device)
      return acc
    }, {} as Record<string, Device[]>)
    return grouped
  })

  // Actions
  const fetchDevices = async() => {
    loading.value = true
    try {
      const result = await deviceAPI.getDevices()
      devices.value = result
    } catch (error) {
      console.error('Failed to fetch devices:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const createDevice = async(deviceData: CreateDeviceRequest) => {
    loading.value = true
    try {
      const deviceId = await deviceAPI.createDevice(deviceData)
      await fetchDevices() // 重新获取设备列表
      return deviceId
    } catch (error) {
      console.error('Failed to create device:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const connectDevice = async(deviceId: string) => {
    try {
      await deviceAPI.connectDevice(deviceId)
      // 更新本地设备状态
      const device = devices.value.find(d => d.id === deviceId)
      if (device) {
        device.status = 'online'
        device.last_heartbeat = new Date().toISOString()
      }
    } catch (error) {
      console.error('Failed to connect device:', error)
      throw error
    }
  }

  const disconnectDevice = async(deviceId: string) => {
    try {
      await deviceAPI.disconnectDevice(deviceId)
      // 更新本地设备状态
      const device = devices.value.find(d => d.id === deviceId)
      if (device) {
        device.status = 'offline'
      }
    } catch (error) {
      console.error('Failed to disconnect device:', error)
      throw error
    }
  }

  const getDeviceScreenshot = async(deviceId: string) => {
    try {
      const screenshot = await deviceAPI.takeDeviceScreenshot(deviceId)
      return screenshot
    } catch (error) {
      console.error('Failed to get device screenshot:', error)
      throw error
    }
  }

  const getDevicePerformance = async(deviceId: string) => {
    try {
      const performance = await deviceAPI.getDevicePerformance(deviceId)
      return performance
    } catch (error) {
      console.error('Failed to get device performance:', error)
      throw error
    }
  }

  const initializeDeviceManager = async() => {
    try {
      await deviceAPI.initializeDeviceManager()
    } catch (error) {
      console.error('Failed to initialize device manager:', error)
      throw error
    }
  }

  const scanAdbDevices = async() => {
    loading.value = true
    try {
      const adbDevices = await deviceAPI.scanAdbDevices()
      // 合并ADB设备和数据库设备
      const existingDevices = await deviceAPI.getDevices()
      devices.value = [...existingDevices, ...adbDevices]
      return adbDevices
    } catch (error) {
      console.error('Failed to scan ADB devices:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const connectAdbDevice = async(deviceId: string) => {
    try {
      await deviceAPI.connectAdbDevice(deviceId)
      // 更新本地设备状态
      const device = devices.value.find(d => d.id === deviceId)
      if (device) {
        device.status = 'online'
        device.last_heartbeat = new Date().toISOString()
      }
    } catch (error) {
      console.error('Failed to connect ADB device:', error)
      throw error
    }
  }

  const disconnectAdbDevice = async(deviceId: string) => {
    try {
      await deviceAPI.disconnectAdbDevice(deviceId)
      // 更新本地设备状态
      const device = devices.value.find(d => d.id === deviceId)
      if (device) {
        device.status = 'offline'
      }
    } catch (error) {
      console.error('Failed to disconnect ADB device:', error)
      throw error
    }
  }

  const selectDevice = (deviceId: string) => {
    if (!selectedDevices.value.includes(deviceId)) {
      selectedDevices.value.push(deviceId)
    }
  }

  const unselectDevice = (deviceId: string) => {
    const index = selectedDevices.value.indexOf(deviceId)
    if (index > -1) {
      selectedDevices.value.splice(index, 1)
    }
  }

  const toggleDeviceSelection = (deviceId: string) => {
    if (selectedDevices.value.includes(deviceId)) {
      unselectDevice(deviceId)
    } else {
      selectDevice(deviceId)
    }
  }

  const selectAllDevices = () => {
    selectedDevices.value = devices.value.map(device => device.id)
  }

  const clearSelection = () => {
    selectedDevices.value = []
  }

  const batchConnect = async() => {
    const promises = selectedDevices.value.map(deviceId => connectDevice(deviceId))
    await Promise.allSettled(promises)
  }

  const batchDisconnect = async() => {
    const promises = selectedDevices.value.map(deviceId => disconnectDevice(deviceId))
    await Promise.allSettled(promises)
  }

  // 获取设备详情
  const getDeviceById = (deviceId: string) => {
    return devices.value.find(device => device.id === deviceId)
  }

  // 更新设备状态（用于实时更新）
  const updateDeviceStatus = (deviceId: string, status: 'online' | 'offline' | 'busy' | 'error' | 'maintenance', heartbeat?: string) => {
    const device = devices.value.find(d => d.id === deviceId)
    if (device) {
      device.status = status
      if (heartbeat) {
        device.last_heartbeat = heartbeat
      }
    }
  }

  return {
    // State
    devices,
    loading,
    selectedDevices,

    // Getters
    deviceCount,
    onlineDeviceCount,
    offlineDeviceCount,
    busyDeviceCount,
    devicesByPlatform,
    devicesByType,

    // ADB Actions
    initializeDeviceManager,
    scanAdbDevices,
    connectAdbDevice,
    disconnectAdbDevice,
    getDevicePerformance,

    // Legacy Actions
    fetchDevices,
    createDevice,
    connectDevice,
    disconnectDevice,
    getDeviceScreenshot,
    selectDevice,
    unselectDevice,
    toggleDeviceSelection,
    selectAllDevices,
    clearSelection,
    batchConnect,
    batchDisconnect,
    getDeviceById,
    updateDeviceStatus
  }
})